<template>
	<div class="p-4">
		<div class="fs_large bold text-center mb-3">安能智保光伏运营期保障方案</div>

		<gridbox class="mb-2" align="center" columns="15px 1fr">
			<div class="fs_large bold p-3"></div>
			<el-radio-group v-model="mode">
				<el-radio label="simgle">单个项目投保</el-radio>
				<el-radio label="multiple">多个项目投保</el-radio>
			</el-radio-group>
		</gridbox>
		<div
			style="margin-bottom: 15px"
			class="shadow business-item"
			v-for="(item, index) in formList"
			:key="item.key"
			:style="{ height: item.__show_form ? 'auto' : '67px' }"
		>
			<VForm style="box-shadow: none" ref="form">
				<flexbox slot="header" justify="flex-end" align="center">
					<span style="flex: 1">
						<span style="padding-left: 10px">投保项目填写</span>
						<span v-if="item.formValue"
							>：{{ item.formValue.baseForm.name }}</span
						>
					</span>
					<el-button
						type="primary"
						@click="item.__show_form = !item.__show_form"
						>{{ item.__show_form ? '收起' : '查看' }}</el-button
					>
					<el-button
						v-show="formList.length > 1"
						plain
						@click="formList.splice(index, 1)"
						>移除</el-button
					>
				</flexbox>
			</VForm>
		</div>
		<div class="text-center mt-4" v-if="mode == 'simgle'">
			<el-button type="primary" @click="onSubmit" :loading="loading">
				下一步，立即完善投保资料
			</el-button>
		</div>
		<div class="text-center mt-4" v-if="mode == 'multiple'">
			<el-button type="primary" plain @click="onInputEnd">
				新增一个光伏项目投保
			</el-button>
			<el-button type="primary" @click="onSubmit" :loading="loading">
				新增完成，立即完善投保资料
			</el-button>
		</div>
	</div>
</template>

<script>
import _ from 'lodash'
import * as REGEXP from '@/const/REGEXP'
import { downloadByResponse } from '@/utils/download'
import moment from 'moment'
var urlSearchParams = new URLSearchParams(location.search)
var UrlSearch = {}
for (let [key, value] of urlSearchParams.entries()) {
	UrlSearch[key] = value
}
import { transformKey } from '@/utils'
import { createPcOrder } from '../api/order'
import { mapGetters } from 'vuex'

import VForm from './vForm'
import { customerById } from '@/api'
let formKey = 0
export default {
	data() {
		return {
			formList: [
				{
					key: formKey++, // 表单序号
					formValue: null, // 表单值(暂存后)
					servError: '', // 后台保存报错
					__show_form: true
				}
			],
			mode: 'multiple',
			loading: false
		}
	},
	computed: {
		...mapGetters(['info'])
	},
	mounted() {},
	methods: {
		// 单个填写完毕
		async onInputEnd() {
			const formRefList = this.$refs.form
			const lastFormIndex = formRefList.length - 1

			// {toubaoForm,beibaoForm,qixianForm,baseForm,riskForm,sameAsToubao}
			const formValue = await formRefList[lastFormIndex].validate()

			this.formList[lastFormIndex].__show_form = false
			this.formList[lastFormIndex].formValue = formValue
			this.formList.push({
				__show_form: true,
				key: formKey++
			})
		},
		onSubmit() {
			if (!this.info?.mobile) {
				this.$store.commit('SET_SHOW_LOGIN_TOAST', true)
				return
			}
			this.submit()
		},
		async submit() {
			const formRefList = this.$refs.form

			const formRefValidates = Array.from(formRefList).map((formRef) =>
				formRef.validate()
			)
			const formValueList = await Promise.all(formRefValidates)

			const postDataList = formValueList.map(this.convertPostData)

			this.loading = true
			const requestList = postDataList.map((postData, index) => {
				return createPcOrder(postData)
					.then(({ data: businessId }) => {
						// 保存完毕的表单将其移除
						this.formList.splice(index, 1)
						simgleBusinessId = businessId
					})
					.catch((res) => {
						this.formList[index].servError = res.msg
					})
					.finally(() => {
						this.loading = false
					})
			})

			var simgleBusinessId
			Promise.all(requestList).then(() => {
				if (this.mode == 'multiple') {
					this.$router.push('/11837/order')
				} else {
					this.$router.push({
						path: '/11837/submit',
						query: {
							businessId: simgleBusinessId
						}
					})
				}
			})
		},

		// 创建请求数据对象
		convertPostData(data) {
			const {
				toubaoForm,
				beibaoForm,
				qixianForm,
				baseForm,
				riskForm,
				sameAsToubao
			} = data
			const subject = { ...baseForm }
			// const [province, city, district] = subject.address
			// subject.address = { province, city, district }

			console.log('convertPostData', data)
			const params = {
				order: {
					money: null,
					extendInfo: {},
					planId: null,
					...qixianForm,
					holder: {
						customerId: toubaoForm.customerId,
						name: toubaoForm.customerName,
						idNum: toubaoForm.certNum,
						// phone: toubaoForm.contactPhone,
						phone: this.info.mobile,
						contactName: toubaoForm.contactName,
						businessLicense: toubaoForm.businessLicense,
						idType: 99,
						detailAddress: toubaoForm.address
					},
					risks: riskForm,
					productId: 11837,
					...UrlSearch
				},
				subjects: [subject]
			}

			if (sameAsToubao) {
				params.order.holder.same = true
			} else {
				params.order.holder.same = false
				params.order.relations = [
					{
						customerId: beibaoForm.customerId,
						name: beibaoForm.customerName,
						idNum: beibaoForm.certNum,
						phone: beibaoForm.contactPhone,
						contactName: beibaoForm.contactName,
						businessLicense: beibaoForm.businessLicense,
						idType: 99,
						detailAddress: beibaoForm.address
					}
				]
			}
			if (this.businessId) {
				params.order.businessId = this.businessId
			}

			return params
		}
	},
	components: { VForm }
}
</script>

<style lang="scss" scoped="scoped">
.business-item {
	overflow: hidden;
	span {
		font-size: 16px;
		font-weight: 600;
	}
}
</style>
